package com.example.javaairportflightanalysis.exception;


import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.util.SaResult;
import com.example.javaairportflightanalysis.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


/**
 * @author shen
 * 处理统一异常的handler
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final Logger log= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e){
        log.error("Exception:",e);
        return ApiRestResponse.error(MyExceptionEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Object handleMallException(MyException e){
        log.error("MallException",e);
        return ApiRestResponse.error(e.getCode(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("MethodArgumentNotValidException:",e);
        return handleBindingResult(e.getBindingResult());
    }

    private ApiRestResponse handleBindingResult(BindingResult result){
//        把异常处理对外暴露的提示
        List<String> list =new ArrayList<>();
        if (result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String message = objectError.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size()==0){
            return ApiRestResponse.error(MyExceptionEnum.REQUEST_PARAM_ERROR);
        }
        return ApiRestResponse.error(MyExceptionEnum.REQUEST_PARAM_ERROR.getCode(),list.toString());
    }

    /**
     * 处理未授权异常
     * @param npe NotPermissionException异常对象
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public SaResult handleNotPermissionException(NotPermissionException npe){
        // 打印堆栈，以供调试
        npe.printStackTrace();
        // 返回给前端
        return SaResult.error("您没有访问权限，请联系管理员");
    }
/**
 * 处理未登录异常
 * @param npe NotLoginException异常对象
 */
@ExceptionHandler(NotLoginException.class)
@ResponseBody
public SaResult notLoginHandler(NotLoginException npe){
    // 打印堆栈，以供调试
    npe.printStackTrace();
    // 返回给前端
    return SaResult.error("您还未登录，请先登录");
}
}
